// pages/index/index.js
import TencentCloudChat from '@tencentcloud/chat';
import TIMUploadPlugin from 'tim-upload-plugin';
import TIMProfanityFilterPlugin from 'tim-profanity-filter-plugin';
import { genTestUserSig } from '../../debug/GenerateTestUserSig';
const app = getApp()
import { requst_get_regions, requst_get_index } from "../../api/login";
import { requst_get_model_list } from '../../api/modelList'
import { wxGetAddress } from '../../utils/util.js'
import {formatTime} from "../../utils/thro"

Page({
  data: {
    system: '',
    navBarHeight: app.globalData.navBarHeight,// 获取导航栏高度
    menuRight: app.globalData.menuRigh,// 获取胶囊距右方间距（方保持左、右间距一致）
    menuTop: app.globalData.menuTop,// 获取胶囊距底部间距（保持底部间距一致）
    menuHeight: app.globalData.menuHeight,// 获取胶囊高度（自定义内容可与胶囊高度保证一致）
    region: ["北京市", "北京市", "东城区"],
    banners: [],
    indicatorDots: true,
    vertical: false,
    autoplay: true,
    interval: 2500,
    duration: 1500,
    circular: true,
    modelData: [],
    isSearchActive: false,
    searchFocus: false,
    searchQuery: '',
    config: {
      userID: '', // User ID
      SECRETKEY: '654b371d6ee2456f6d03d9ec46dcd2e1d8fbd4fa4712a9974df98b4202d3a1e1', // Your secretKey
      SDKAPPID: 1600041146, // Your SDKAppID
      EXPIRETIME: 604800,
    },
  },

  async onLoad() {
    this.getLocation();
    const res = await wx.getStorage({
      key: 'user'
    })
    if (res.data.limits_id == '1') {
      this.setData({
        'config.userID': res.data.model_basic.nickname,
      })
    } else {
      this.setData({
        'config.userID': res.data.user_basic.nickname,
      })
    }
    requst_get_index({}).then(res => {
      this.setData({ banners: res.data.banners })
    })
    requst_get_model_list({ page: 1, limit: 5, hot: 2 }).then(res => {
      this.setData({
        modelData: res.data.data
      })
    })
    wx.getSystemInfo({
      success: res => {
        this.setData({
          system: res
        });
      }
    })
    wx.$TUIKit = TencentCloudChat.create({
      SDKAppID: this.data.config.SDKAPPID,
    });
    const userSig = genTestUserSig(this.data.config).userSig
    wx.$chat_SDKAppID = this.data.config.SDKAPPID;
    wx.TencentCloudChat = TencentCloudChat;
    wx.$chat_userID = this.data.config.userID;
    wx.$chat_userSig = userSig;
    wx.$TUIKit.registerPlugin({ 'tim-upload-plugin': TIMUploadPlugin });
    wx.$TUIKit.registerPlugin({ 'tim-profanity-filter-plugin': TIMProfanityFilterPlugin });
    wx.$TUIKit.login({
      userID: this.data.config.userID,
      userSig
    });
    // 监听系统级事件
    wx.$TUIKit.on(wx.TencentCloudChat.EVENT.SDK_READY, this.onSDKReady, this);

  },
  getLocation() {
    wx.getLocation({
      type: 'gcj02',
      success: async res => {
        let { longitude, latitude } = res;
        let result = await wxGetAddress(longitude, latitude);
        this.setData({
          region: [result.regeocodeData.addressComponent.province, result.regeocodeData.addressComponent.city, result.regeocodeData.addressComponent.district]
        })
      }
    });
  },
  bindRegionChange(e) {
    this.setData({
      region: e.detail.value
    })

  },
  toggleSearch: function () {
    // this.setData({
    //   isSearchActive: !this.data.isSearchActive,
    //   searchFocus: !this.data.searchFocus
    // });
    wx.navigateTo({
      url: `/subPackages/pages/search/search`
    });
  },
  onInput: function (e) {
    this.setData({
      searchQuery: e.detail.value
    });
  },
  toModelDetails: function (event) {
    wx.navigateTo({
      url: '/subPackages/pages/modelDetails/modelDetails?value=' + JSON.stringify(event.currentTarget.dataset.bean)
    });

  },
  moveToModelList: function (e) {
    const index = e.currentTarget.dataset['index'];
    wx.navigateTo({
      url: '/subPackages/pages/modelList/modelList?index=' + index
    });
  },
  jumpFun(e) {
    let type = e.currentTarget.dataset.bean.skip_id
    let content = e.currentTarget.dataset.bean.Jump_position
    wx.showToast({
      title: type,
    })
    switch (type) {
      case '0':
        return
      case '1':
        wx.navigateTo({
          url: '/subPackages/pages/modelDetails/modelDetails?value=' + JSON.stringify({ users_uid: content })
        });
        this.setData({ banners: this.data.banners })
        break
      case '2':
        wx.navigateTo({
          url: '/subPackages/pages/modelList/modelList?index=' + content
        });
        this.setData({ banners: this.data.banners })
        break
      case '3':
        wx.switchTab({
          url: '/pages/activity/activity',
        })
        this.setData({ banners: this.data.banners })
        break
      case '4':
        wx.switchTab({
          url: '/pages/circle/circle',
        })
        this.setData({ banners: this.data.banners })
        break
    }
  },
  async onShareAppMessage(res) {
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res)
    }
    let data = await wx.getStorageSync('user')
    let params = {
      title: '现在注册享多重好礼',
      imageUrl: 'https://mote.sunchanghao.top/image//login_avatar.png',
      path: `/pages/loading/loading?value=${data.id}`
    }
    return params
  },
  onShow() {
    // TODO 待删
    let curDate=formatTime(new Date())
    console.log(curDate,'curDate============')
    //自定义的tabbar
    if (typeof this.getTabBar === 'function' &&
      this.getTabBar()) {
      this.getTabBar().setData({
        selected: 0
      })
    }
    wx.getStorage({
      key: "redirect",
      success(res) {
        if (res.data.redirect == "circleExperienceDetails") {
          wx.showToast({
            title: '正在跳转至经验',
            icon: 'none1'
          })
          wx.navigateTo({
            url: '/subPackages/pages/circleExperienceDetails/circleExperienceDetails?id=' + res.data.params,
          })
        }
        wx.setStorage({
          key: "redirect",
          data: {}
        })
      },
    });
  }
});
